/*
 * Created by JFormDesigner on Thu Nov 06 17:38:56 CST 2025
 */

package com.yeban.bams.server;

import java.awt.event.*;
import com.yeban.bams.server.manager.LoginInfo;
import com.yeban.bams.server.manager.LoginManager;

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

/**
 * @author yeban
 */
public class RankPanel extends JPanel {
    private ATMServer atm;

    private DefaultTableModel tableModel;
    private Timer timer;

    public RankPanel(ATMServer atm) {
        this.atm = atm;
        initComponents();
        initTable();    // 初始化表格
        startRefresh(); // 开启自动刷新
        LoginManager.setListener(this::refreshTableData); // 即时刷新
    }

    /**
     * 初始化表格（不可编辑）
     */
    private void initTable() {
        String[] columnNames = {"时间", "账户", "IP"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override public boolean isCellEditable(int row, int column) { return false; }
        };
        LoginTable.setModel(tableModel);
        LoginTable.setEnabled(true);
    }

    /**
     * 刷新表格数据
     */
    private void refreshTableData() {
        SwingUtilities.invokeLater(() -> {
            tableModel.setRowCount(0);  // 清空旧数据
            for(LoginInfo info : LoginManager.getLoginMap().values()) {
                Object[] row = {info.getDisplayTime(), info.getAccId(), info.getIp()};  // 把数据封装
                tableModel.addRow(row);
            }
        });
    }

    /**
     * 开始自动刷新
     */
    public void startRefresh() {
        if (timer == null) {
            timer = new Timer(3000, e -> refreshTableData());
            timer.start();
        }
    }

    /**
     * 关闭自动刷新
     */
    public void stopRefresh() {
        if(timer != null) {
            timer.stop();   // 停止
            timer = null;   // 标志位滞空
        }
    }

    /**
     * 返回服务端首页
     */
    private void back(ActionEvent e) {
        stopRefresh();
        CardLayout cardLayout = (CardLayout)atm.getContentPane().getLayout();
        cardLayout.show(atm.getContentPane(), "serverPanel");
    }

    /**
     * 清空登录列表
     */
    public void clear() {
        if (tableModel != null) {
            tableModel.setRowCount(0);
        }
    }

    /**
     * 进入更多信息页面
     */
    private void moreInfo(ActionEvent e) {
        stopRefresh();
        atm.dataPanel.reload(); // 进入DataPanel前：清空并刷新
        CardLayout cardLayout = (CardLayout)atm.getContentPane().getLayout();
        cardLayout.show(atm.getContentPane(), "dataPanel");
    }

    /**
     * 进入实时日志显示页面
     */
    private void log(ActionEvent e) {
        stopRefresh();
        CardLayout cardLayout = (CardLayout)atm.getContentPane().getLayout();
        cardLayout.show(atm.getContentPane(), "logPanel");
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        loginSessionLabel = new JLabel();
        panel1 = new JPanel();
        backButton = new JButton();
        scrollPane1 = new JScrollPane();
        LoginTable = new JTable();
        moreInfoButton = new JButton();
        logButton = new JButton();

        //======== this ========
        setLayout(null);

        //---- loginSessionLabel ----
        loginSessionLabel.setText("\u767b  \u5f55  \u8868");
        loginSessionLabel.setHorizontalAlignment(SwingConstants.CENTER);
        loginSessionLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 30));
        add(loginSessionLabel);
        loginSessionLabel.setBounds(115, 40, 275, 65);

        //======== panel1 ========
        {
            panel1.setLayout(null);

            {
                // compute preferred size
                Dimension preferredSize = new Dimension();
                for(int i = 0; i < panel1.getComponentCount(); i++) {
                    Rectangle bounds = panel1.getComponent(i).getBounds();
                    preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                    preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                }
                Insets insets = panel1.getInsets();
                preferredSize.width += insets.right;
                preferredSize.height += insets.bottom;
                panel1.setMinimumSize(preferredSize);
                panel1.setPreferredSize(preferredSize);
            }
        }
        add(panel1);
        panel1.setBounds(new Rectangle(new Point(45, 140), panel1.getPreferredSize()));

        //---- backButton ----
        backButton.setText("\u8fd4\u56de");
        backButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
        backButton.addActionListener(e -> back(e));
        add(backButton);
        backButton.setBounds(370, 550, 100, 45);

        //======== scrollPane1 ========
        {

            //---- LoginTable ----
            LoginTable.setModel(new DefaultTableModel(
                new Object[][] {
                    {null, null, null},
                    {null, null, null},
                },
                new String[] {
                    "\u65f6\u95f4", "\u8d26\u6237", "IP"
                }
            ));
            scrollPane1.setViewportView(LoginTable);
        }
        add(scrollPane1);
        scrollPane1.setBounds(25, 115, 440, 420);

        //---- moreInfoButton ----
        moreInfoButton.setText("\u66f4\u591a\u4fe1\u606f");
        moreInfoButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
        moreInfoButton.addActionListener(e -> moreInfo(e));
        add(moreInfoButton);
        moreInfoButton.setBounds(235, 550, 120, 45);

        //---- logButton ----
        logButton.setText("\u65e5\u5fd7\u4fe1\u606f");
        logButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
        logButton.addActionListener(e -> log(e));
        add(logButton);
        logButton.setBounds(100, 550, 120, 45);

        setPreferredSize(new Dimension(500, 650));
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel loginSessionLabel;
    private JPanel panel1;
    private JButton backButton;
    private JScrollPane scrollPane1;
    private JTable LoginTable;
    private JButton moreInfoButton;
    private JButton logButton;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
